<template>
  <el-upload
    class="avatar-uploader"
    :action="uploadUrl"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :headers="uploadHeaders"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script setup>
import { ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { useAdminStore } from "@/stores/adminStore";

const props = defineProps(["initialImage"]);

const token = useAdminStore().adminInfo.token;
const uploadUrl = "http://localhost:8080/admin/common/upload";
const uploadHeaders = { Authorization: "Bearer " + token };
const imageUrl = ref(props.initialImage || "");

watch(
  () => props.initialImage,
  (newVal) => {
    imageUrl.value = newVal;
  }
);

const emit = defineEmits(["sendImage"]);

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isImage) {
    ElMessage.error("上传文件只能是图片!");
  }
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过 2MB!");
  }
  return isImage && isLt2M;
};

const handleAvatarSuccess = (res) => {
  if (res.data) {
    imageUrl.value = res.data;
    ElMessage.success("图片上传成功");
    emit("sendImage", imageUrl.value);
  } else {
    console.error("无效的响应数据"); 
  }
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 200x;
  height: 200px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>